package com.szy.douyou_article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szy.douyou_article.config.ResultDTO;
import com.szy.douyou_article.dao.Friend;
import com.szy.douyou_article.dao.Users;
import com.szy.douyou_article.dao.mapper.FriendMapper;
import com.szy.douyou_article.service.FriendService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author sunziyan
 * @date 2022/4/19
 */
@Service
public class FriendServiceImpl implements FriendService {
    @Resource
    private FriendMapper friendMapper;


    @Override
    public ResultDTO saveChatHistory(Friend friend) {
        Integer result = friendMapper.update(friend, new QueryWrapper<Friend>().eq("user_id", friend.getUserId()).eq("friend_id", friend.getFriendId()));
        return ResultDTO.success(result);
    }

    @Override
    public ResultDTO getChatHistory(Friend friend) {
        friend = friendMapper.selectOne(new QueryWrapper<Friend>().eq("user_id", friend.getUserId()).eq("friend_id", friend.getFriendId()));
        if(friend == null){
            return ResultDTO.fail("没有朋友关系");
        }
        return ResultDTO.success(friend.getChatHistory());
    }

    @Override
    public Set<String> getFriendIdByUserId(Long userId) {
        List<Friend> friendList = friendMapper.selectList(new QueryWrapper<Friend>().eq("user_id",userId));
        Set<String> friendId = new HashSet<>();
        friendId.add(userId.toString());
        for (Friend friend : friendList){
            friendId.add(friend.getFriendId().toString());
        }
        return friendId;
    }

    @Override
    public ResultDTO insertFriend(Friend friend) {
        Friend friend1 = new Friend();
        friend1.setUserId(friend.getFriendId());
        friend1.setFriendId(friend.getUserId());

        friendMapper.insert(friend);
        friendMapper.insert(friend1);
        return ResultDTO.success();
    }

    @Override
    public ResultDTO getMyFriend(Long userId,int pageNo,int pageSize) {
        Page<Users> usersPage = new Page<>(pageNo,pageSize);
        usersPage = friendMapper.selectFriendList(usersPage,userId);

        return ResultDTO.success(usersPage);
    }


}
